import java.io.*;
import java.util.*; // ArrayList, TreeSet
import org.apache.commons.lang3.StringUtils;

public class CourseList {

	private static String COURSE_FILE_HEADER = "# format: " +
	                                           "courseID," +
	                                           "startDate - endDate," +
	                                           "courseName," +
	                                           "courseSummary," +
	                                           "maxEnrolled," +
	                                           "currentEnrolled\n";

	/** 
	* Reads and parses a text file, containing a list of courses, 
	* and builds a TreeSet of Course objects.    
	*
	* @param	courseFile		filename of text file to read
	* @return	courseList		TreeSet of Course objects
	*/
	public static TreeSet<Course> readCourseList(String courseFile) {

		TreeSet<Course> courseList = new TreeSet<Course>();
		
		try {
			FileReader reader = new FileReader(new File(courseFile));
			BufferedReader buffer = new BufferedReader(reader);
			String line = null;

			// Read each line from CourseList.txt, and create a new Course
			// for each line.  Create a TreeSet of courses.

			// skip the first line, which identifies the fields
			buffer.readLine();
			while ((line = (buffer.readLine())) != null) {
				Course newCourse = createCourse(line);
				courseList.add(newCourse);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return courseList;	
	}    

	/** 
	* Writes a text file, containing a list of courses, including number of students
	* enrolled in each course, using data from a TreeSet of Course objects.  
	* If there is an existing text file with the same name, it will be overwritten.
	*
	* @param	courseFile		filename of text file to write
	* @param	courses			TreeSet of Course objects to be written out
	*/
	public static void writeCourseList(TreeSet<Course> courses, String courseFile) {

		try {
			// Create a file containing all of the courses, as updated.
			BufferedWriter writer = new BufferedWriter(new FileWriter(courseFile));
			
			// Write the first line, which documents the fields
			writer.write(COURSE_FILE_HEADER);
			
			for (Course c : courses)
			{
				writer.write(courseOutput(c) + "\n");
			}
			writer.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return;		
	}

	/** 
	* Finds and returns a Course, in the input TreeSet, with the specified courseID.
	* If no match is found, the returned object reference is null.  
	*
	* @param	courseID		ID of the course to find
	* @param	courseList		TreeSet of Course objects to be searched
	* @return	Course object with the specified courseID, or null if not found
	*/
	public static Course getCourse(String courseID, TreeSet<Course> courseList) {
		// Find the course with the specified ID in the courseList.
		Course foundCourse = null;
		for (Course c : courseList) {
			if (c.getID().equals(courseID)) {
				foundCourse = c;
				break;
			}
		}
		return foundCourse;
	}

    private static Course createCourse(String line) {
		// Parse the input line into tokens, and use them to create a Course.
		// Each line in CourseList.txt contains: 
		// courseID,startDate - endDate,courseName,courseSummary,maxEnrolled,currentEnrolled
		String[] tokens = line.split(",");

/* Course constructor expects parameters in this order:
		this.courseName      = courseName;
		this.courseID        = courseID;
		this.maxEnrolled     = maxEnrolled;
		this.currentEnrolled = currentEnrolled;
		this.startDate       = startDate;
		this.endDate         = endDate;
		this.courseSummary   = courseSummary;
*/

		Course nextCourse = new Course(
			tokens[2], // courseName
			tokens[0], // courseID
			Integer.parseInt(tokens[4]), // maxEnrolled
			Integer.parseInt(tokens[5]), // currentEnrolled
			StringUtils.substringBefore(tokens[1], " - "), // start date
			StringUtils.substringAfter(tokens[1], " - "), // end date
			tokens[3]); // courseSummary
		return nextCourse;
    }
    
    private static String courseOutput(Course c) {
		// Create a comma-delimited string holding this Course's info.
		// Each line in CourseList.txt contains: 
		// courseID,startDate - endDate,courseName,courseSummary,maxEnrolled,currentEnrolled
    	return String.format("%s,%s - %s,%s,%s,%d,%d", 
    		c.getID(),
    		c.getStartDate(),
    		c.getEndDate(),
    		c.getName(),
    		c.getSummary(),
    		c.getMaxEnrolled(),
    		c.getCurrentEnrolled());
    }
}
